package com.yenlien.traceyun.control.service;

import com.yenlien.traceyun.control.dao.LoanInfoDao;
import com.yenlien.traceyun.control.dao.RepaymentDao;
import com.yenlien.traceyun.control.entity.*;
import com.yenlien.traceyun.control.interceptor.UserAuthUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

//还款计划表
@Service
public class RepaymentService {

    @Autowired
    private RepaymentDao repaymentDao;

    @Autowired
    private LoanInfoDao loanInfoDao;

    public Page<Repayment> findByList(final Repayment repayment) {
        Pageable pageable = PageRequest.of(repayment.getPage(), repayment.getPageSize(), Sort.Direction.DESC, "createTime");
        return repaymentDao.findAll(new Specification<Repayment>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<Repayment> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                if (repayment.getRepaymentTime() != null) {
                    list.add(cb.equal(root.get("repaymentTime"), repayment.getRepaymentTime()));        //根据传的状态筛选
                }
                if (StringUtils.isNotEmpty(repayment.getName())) {
                    list.add(cb.equal(root.get("name"), repayment.getName()));        //根据传的状态筛选
                }
                if (StringUtils.isNotEmpty(repayment.getReviewer())) {
                    list.add(cb.equal(root.get("reviewer"), repayment.getReviewer()));        //根据传的状态筛选
                }
                if (StringUtils.isNotEmpty(repayment.getLoanId())) {
                    list.add(cb.equal(root.get("loanId"), repayment.getLoanId()));        //loanId
                } else {
                    if (StringUtils.isNotEmpty(repayment.getCompanyId())) {
                        list.add(cb.equal(root.get("companyId"), repayment.getCompanyId()));        //公司ID
                    }
                }
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        }, pageable);
    }

    /**
     * 合作社用户发起还款请求，银行端管理员审核还款信息
     */
    public Object save(Repayment repayment) {
        String id = repayment.getId();
        if (StringUtils.isNotEmpty(id)) {     //更新操作
            Repayment pay = repaymentDao.findById(repayment.getId()).get();
            if (pay != null) {
                if (pay.getStatus().equals("0")) {    //用户还款的操作,   申请成功
//                    repayment.getRealAmount();      //实际还款金额=每月还款金额
                    BigDecimal realAmount = pay.getAmount();
                    String status = repayment.getStatus();
                    return repaymentDao.updateRepay(id, new Date(), realAmount, status);           //实际还款时间
                } else if (pay.getStatus().equals("1")) {          //审核还款
                    repayment.setReviewer(UserAuthUtil.getLoginUser().getUsername());
                    String status = repayment.getStatus();
                    BigDecimal surplusAmount = pay.getSurplusAmount();        //剩余还款金额
                    BigDecimal surplusAm = surplusAmount.subtract(pay.getRealAmount()).setScale(2, RoundingMode.HALF_UP);

                    Integer bySumNum2 = repaymentDao.findBySumNum2(repayment.getLoanId());  //已经还金额
                    BigDecimal bigDecimal = bySumNum2 != null ? new BigDecimal(bySumNum2) : pay.getAmount();
                    repaymentDao.updateRepay3(repayment.getLoanId(), surplusAm, bigDecimal);           //改变所有的剩余还款金额
                    return repaymentDao.updateRepay2(id, status, new Date());         // 2.还款成功  -1：还款失败
                }

            }
        }
        return null;
    }

    /**
     * 查询单个
     */
    public Object findById(String id) {
        return repaymentDao.findById(id);
    }

    /**
     * 生成还款计划表
     */
    public Object pay(Repayment repayment) {
        int loanPeriod = repayment.getLoanPeriod();
        List<Repayment> li = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Date time = null;
        int j = 1;
        int f = loanPeriod;
        BigDecimal totalMoney = repayment.getAmount().multiply(new BigDecimal(loanPeriod)).setScale(2, RoundingMode.HALF_UP);
        for (int i = 0; i < loanPeriod; i++) {
            calendar.add(Calendar.MONTH, 1);
            time = calendar.getTime();
            Repayment repay = new Repayment();
            repay.setCreateTime(new Date());            //创建时间
            repay.setRealAmount(new BigDecimal(0.00));      //已还金额
            repay.setRepaidAmount(new BigDecimal(0.00));
            repay.setSurplusAmount(totalMoney);           //剩余还款金额
            repay.setAmount(repayment.getAmount());          //还款金额
            repay.setName(repayment.getName());         //还款人
            repay.setSurplusNum(--f);     ////剩余期数
            repay.setRepaymentNum("第" + (j++) + "期");         //还款期数
            repay.setRepaymentTime(time);           //还款时间
            repay.setLoanPeriod(loanPeriod);         //总期数
            repay.setReviewer(repayment.getReviewer());         //审核人
            repay.setRate(repayment.getRate());         //贷款利率传JSONObject;
            repay.setStatus("0");
            repay.setRemarks(repayment.getRemarks());
            repay.setLoanId(repayment.getLoanId());         //申请贷款关联id
            repay.setBankInfoId(repayment.getBankInfoId());
            repay.setCompanyId(repayment.getCompanyId());
            li.add(repay);
        }
        return repaymentDao.saveAll(li);
    }
}
